package com.itheima.health.service.impl;

import com.itheima.health.common.RedisConst;
import com.itheima.health.service.SendCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

/**
 * @Author: liangWeiQUQ
 * @Description: TODO
 * @DateTime: 2021/3/5 11:58
 **/
@DubboService
@Slf4j
public class SendCodeServiceImpl implements SendCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
       * @Author: 传闻中的梁大侠
       * @Date: 12:02 2021/3/5
       * @Parms [type, telephone]
       * @ReturnType: void
       * @Description: 短信发送验证码
     */

    @Override
    public void sendCode(String type, String telephone) {
        //1.生成验证码
        SecureRandom secureRandom = new SecureRandom();
        int code = (int) (secureRandom.nextDouble() * 8999 + 1000);
        //2.将生成的验证码放入到redis中
        redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PRE + type + "_" + telephone).set(code, 30, TimeUnit.SECONDS);
        //3.发送验证码
        log.info("[发送验证码]code ： {}", code);
    }
    /**
     * @Author: 传闻中的梁大侠
     * @Date: 11:20 2021/3/4
     * @Parms [param]
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 提交预约信息实现功能之验证码实现功能
     */
    @Override
    public boolean checkCode(String order, String telephone, String validateCode) {
        //得到redis中的验证码
        int code = (int) redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PRE + order + "_" + telephone).get();
        //得到的验证码与前端的验证码进行对比
        if (validateCode.equals(String.valueOf(code))) {
            return true;
        }
        return false;
    }
}
